package com.matrix.im.infrastructure.persistence.repository.impl;

import com.matrix.im.domain.model.SystemMessage;
import com.matrix.im.domain.repository.SystemMessageRepository;
import com.matrix.im.infrastructure.persistence.repository.SystemMessageMongoRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Repository;

import java.util.Optional;

/**
 * @author 有点甜
 * @since 2025/8/2
 */
@Repository
@RequiredArgsConstructor
public class SystemMessageRepositoryImpl implements SystemMessageRepository {

    private final SystemMessageMongoRepository mongoRepository;

    @Override
    public void save(SystemMessage message) {
        mongoRepository.save(message);
    }

    @Override
    public Optional<SystemMessage> findById(String messageId) {
        return mongoRepository.findById(messageId);
    }

    @Override
    public Page<SystemMessage> findByUserId(Long userId, int pageNum, int pageSize) {
        PageRequest pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by("timestamp").descending());
        return mongoRepository.findByUserId(userId, pageable);
    }

    @Override
    public long countUnread(Long userId) {
        return mongoRepository.countByUserIdAndIsRead(userId, false);
    }
}
